<template>
  <div class="personalwhole">
    <div class="title">我的资料</div>
    <div class="subject">
      <a-form hideRequiredMark class="addForm" :form="form" @submit="handleSubmit">
        <div class="one">
          <span class="preview">头像预览</span>
          <img class="imgFile" :src="userPortrait?userPortrait:imgUrl+userInfo.avatar?imgUrl+userInfo.avatar:userImg" alt />
          <a-upload
            accept="image/jpeg, image/jpg, image/png"
            name="file"
            :show-upload-list="false"
            :customRequest="uploadImage"
            :before-upload="beforeUpload"
          >
            <a-button :class="portraitBut">更换头像</a-button>
          </a-upload>
          <span class="format">支持jpg、jpeg、png 格式图片</span>
        </div>
        <div class="two">
          <a-form-item class="aFormItem" v-bind="formItemLayout" label="姓名">
            <a-input
              class="inp"
              v-decorator="[
            'nickName',
            {
              rules: [
                {
                  required: true,
                  message: '请输入姓名',
                },
              ],
            },
          ]"
            />
          </a-form-item>
          <span class="reminder"></span>
        </div>
        <div class="three">
          <a-form-item class="aFormItem" v-bind="formItemLayout" label="用户名">
            <a-input
              class="inp"
              v-decorator="[
            'userName',
            {
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                },
              ],
            },
          ]"
            />
          </a-form-item>
          <span class="reminder">修改用户名，并保证用户名唯一</span>
        </div>
        <div class="four">
          <a-form-item class="aFormItem" v-bind="formItemLayout" label="旧密码">
            <a-input
              class="inp"
              type="password"
              v-decorator="[
            'oldPassword',
            {
              rules: [
                { min: 6, message: '密码最少6位', trigger: 'blur' },
              ],
            },
          ]"
            />
          </a-form-item>
          <span class="reminder">最少6个字符</span>
        </div>
        <div class="five">
          <a-form-item class="aFormItem" v-bind="formItemLayout" label="新密码">
            <a-input
              class="inp"
              type="password"
              v-decorator="[
            'newPassword',
            {
              rules: [
                { min: 6, message: '密码最少6位', trigger: 'blur' },
              ],
            },
          ]"
            />
          </a-form-item>
          <span class="reminder">最少6个字符</span>
        </div>
        <div class="six">
          <!-- <a-button class="but" @click="submitMessage">提交</a-button> -->
          <a-button type="primary" html-type="submit" :class="but">提交</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script>
import uploadApi from "../../api/uploadImage/uploadImage.js";
import api from "../../api/login/login.js";
// 获取字符串中 指定字符的前面 与 后面
function getStr(string, str) {
    var str_before = string.split(str)[0];
    var str_after = string.split(str)[1];
    var obj = {
        goods: str_before,
        goods_id: str_after
    };
    return obj;
}
export default {
  inject: ['reload'],
  data() {
    return {
      userInfo: {},
      userImg: require("../../../images/home/doctor.png"),
      imgUrl: "/profile",
      Portrait:'',
      userPortrait: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0
          },
          sm: {
            span: 16,
            offset: 8
          }
        }
      },
      but:'but',
      portraitBut:'portraitBut'
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "register" });
  },
  created() {
    // this.userInfo = this.$store.state.userInfo;
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    this.imgUrl = this.$config.imgUrl;
  },
  mounted() {
    let _this = this;
    this.form.setFieldsValue({
      nickName: this.userInfo.nickName,
      userName: this.userInfo.userName
    });
    window.Event.$on("menuLeft", val => {
      _this.menuLeft = val;
      if (_this.menuLeft != "menuDeaDolour") {
        _this.but='but';
        _this.portraitBut='portraitBut';
      } else if (_this.menuLeft == "menuDeaDolour") {
        _this.but='but1';
        _this.portraitBut='portraitBut1';
      }
    });
    // _this.menuLeft1 = _this.$store.state.menuLeft;
    _this.menuLeft1 = sessionStorage.getItem('menuLeft')
    if (_this.menuLeft1 != "menuDeaDolour") {
      _this.but='but';
        _this.portraitBut='portraitBut';
    } else if (_this.menuLeft1 == "menuDeaDolour") {
      _this.but='but1';
        _this.portraitBut='portraitBut1';
    }
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpeg、 jpg、png格式的图片!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("不能大于2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    // 上传图片
    uploadImage(file) {
      let _this = this;
      let formData = new FormData();
      formData.append("chunk", file.file);
      formData.append("hash", file.file.uid);
      formData.append("filename", file.file.name);
      uploadApi.uploadImage(null, formData).then(
        res => {
          if (res.code == 200) {
            if(res.data != '') {
              _this.Portrait = res.data;
              _this.userPortrait = _this.imgUrl + res.data;
            }else {
              _this.userPortrait = '';
              _this.reload()
            }
          }
        },
        err => {}
      );
    },
    handleSubmit(e) {
      let _this = this;
      e.preventDefault();
      _this.form.validateFields((err, values) => {
        let imgFile = document.querySelector('.imgFile');
        let str = getStr(imgFile.src, 'files/');
        values.avatar = str.goods_id;
        if (values.oldPassword == undefined) {
          values.oldPassword = "";
        }
        if (values.newPassword == undefined) {
          values.newPassword = "";
        }
        if (!err) {
          if(values.newPassword =="" && values.oldPassword !="") {
            _this.$message.error("请输入新密码");
          }
          api.userUpdate(null, values).then(res => {
            console.log(res)
            if(values.oldPassword !="" && values.newPassword != "") {
              if(res.code == 200) {
                _this.$message.success("修改成功,重新登录");
                setInterval(()=>{
                  window.sessionStorage.clear();
                  this.$store.commit("mutUserToken", "");
                  this.$store.commit("mutUserInfo", {});
                  this.$router.push("/");
                },2000)
              }else {
                _this.$message.error(res.message);
              }
              if(res.message == "已存在此用户名") {
                _this.$message.error(res.message);
              }
            }
            if(values.oldPassword =="" && values.newPassword == "") {
              if(res.code == 200) {
                _this.$message.success("修改成功");
                let message = JSON.parse(sessionStorage.getItem('userInfo'))
                message.avatar = values.avatar;
                message.nickName = values.nickName;
                message.userName = values.userName;
                message = JSON.stringify(message);
                window.sessionStorage.setItem("userInfo", message);
                this.$parent.$parent.$parent.userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
                this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
              }
              if(res.message == "已存在此用户名") {
                _this.$message.error(res.message);
              }
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.personalwhole {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  height: 100%;
  .title {
    font-size: 18px;
    color: #4d4d4d;
    line-height: 50px;
    margin-left: 30px;
  }
  .subject {
    margin-left: 30px;
    width: 1560px;
    height: 760px;
    background: #ffffff;
    border: 1px solid #c4d7e1;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .one {
      width: 900px;
      height: 220px;
      background: #eff2f4;
      margin-top: 66px;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      .preview {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        margin: 0 42px 0 30px;
      }
      img {
        width: 158px;
        height: 158px;
        border-radius: 50%;
        margin-right: 83px;
      }
      .portraitBut {
        margin-right: 50px;
        width: 120px;
        height: 30px;
        background: #ffffff;
        border: 1px solid #0078b6;
        color: #0078b6;
        border-radius: 15px;
      }
      .portraitBut1 {
        margin-right: 50px;
        width: 120px;
        height: 30px;
        background: #ffffff;
        border: 1px solid #2091bd;
        color: #2091bd;
        border-radius: 15px;
      }
      .format {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #747474;
      }
    }
    .two,
    .three,
    .four,
    .five {
      width: 900px;
      height: 80px;
      background: #eff2f4;
      margin-top: 10px;
      display: flex;
      align-items: center;
      .inp {
        width: 360px;
        height: 36px;
        background: #ffffff;
      }
      .reminder {
        font-size: 16px;
        color: #747474;
        margin-left: 50px;
      }
    }
    .six {
      width: 900px;
      display: flex;
      margin-top: 41px;
      .but {
        width: 94px;
        height: 30px;
        background: #0078b6;
        border-radius: 15px;
        font-size: 16px;
        color: #ffffff;
        margin-bottom: 20px;
      }
      .but1 {
        width: 94px;
        height: 30px;
        background: #2091bd;
        border-radius: 15px;
        font-size: 16px;
        color: #ffffff;
        margin-bottom: 20px;
      }
    }
  }
}
</style>
<style>
.personalwhole .aFormItem.ant-row.ant-form-item {
  height: 80px !important;
}
.personalwhole .ant-col.ant-col-xs-24.ant-col-sm-8.ant-form-item-label {
  width: 100px !important;
  display: flex !important;
  justify-content: flex-start !important;
  padding-left: 30px !important;
  margin-right: 40px !important;
  line-height: 80px !important;
}
.personalwhole .ant-col.ant-col-xs-24.ant-col-sm-16.ant-form-item-control-wrapper {
  height: 36px !important;
  margin-top: 20px !important;
}
.personalwhole .ant-form-item {
  margin-bottom: 0 !important;
}
</style>
